<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">

          <a-col :md="4" :sm="8">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="储值车类型">
              <a-select v-model="queryParam.carTypeId" :options="carTypeOptions"></a-select>
            </a-form-item>
          </a-col>

          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="开始日期" @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="4">
            <a-form-item>
              <a-date-picker placeholder="结束日期" @change="onChangeEndTime"/>
            </a-form-item>

          </a-col>

          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>

            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('储值车信息')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleRecharge(record)">充值</a>
          <a-divider type="vertical"/>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
          <a-divider type="vertical"/>
          <a @click="writeOff(record)">核销</a>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <parkCarStored-modal ref="modalForm" @Refresh="Refresh"></parkCarStored-modal>
    <ParkCarStoredRechargeModal ref="rechargeModal" @Refresh="Refresh"></ParkCarStoredRechargeModal>
  </a-card>
</template>

<script>
import ParkCarStoredModal from './modules/ParkCarStoredModal'
import ParkCarStoredRechargeModal from "./modules/ParkCarStoredRechargeModal";
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile,postAction} from '@api/manage'
import {filterObj} from '@/utils/util';

export default {
  name: "ParkCarStoredList",
  mixins: [JeecgListMixin],
  components: {
    ParkCarStoredModal,
    ParkCarStoredRechargeModal
  },
  data() {
    return {
      description: '储值车信息管理页面',

      url: {
        list: "/parkCar/parkCarStored/list",
        delete: "/parkCar/parkCarStored/delete",
        writeOff: "/parkCar/parkCarStored/writeOff",
        carTypeLoad:"/parkCar/parkCarStored/getStoreCarTypeList",
        deleteBatch: "/parkCar/parkCarStored/deleteBatch",
        exportXlsUrl: "parkCar/parkCarStored/storeExportXls",
      },
      queryParam: {
        "createTime_begin": "",
        "createTime_end": "",
        "type": "-1",
        "carTypeId":''
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      carTypeOptions:[],
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '车牌号',
          align: "center",
          dataIndex: 'plateNo',
          width: 70
        },
        {
          title: '停车场编号',
          align: "center",
          dataIndex: 'parkCode',
          width: 70
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName',
          width: 100
        },

        {
          title: '客户姓名',
          align: "center",
          dataIndex: 'userName',
          width: 80
        },
        {
          title: '客户手机号码',
          align: "center",
          dataIndex: 'mobile',
          width: 100
        },
        {
          title: '余额（元）',
          align: "center",
          dataIndex: 'payFee',
          width: 100
        },
        {
          title: '修改时间',
          align: "center",
          dataIndex: 'updateTime',
          width: 100
        },
        {
          title: '创建人',
          align: "center",
          dataIndex: 'createUser',
          width: 100
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime',
          width: 100
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
          width: 120
        }
      ],
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {

    this.keyupEnter()
    this.loadCarTypeData()
  },
  methods: {
    writeOff(record){
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "查看";
      this.$refs.modalForm.disableSubmit = false;
      this.$refs.modalForm.payAlias = '余额(元)';
      this.$refs.modalForm.disableBalance = true;
      this.$refs.modalForm.readOnly=true;
      Object.assign(this.$refs.modalForm.carTypes,this.carTypeOptions)
      if(this.$refs.modalForm.carTypes.length>1)
      {
        this.$refs.modalForm.carTypes.shift()
      }else {
        this.$message.error("请先导入车辆信息")
      }
    },

    handleEdit: function (record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
      this.$refs.modalForm.payAlias = '余额(元)';
      this.$refs.modalForm.disableBalance = true
      this.$refs.modalForm.readOnly=false;
      Object.assign(this.$refs.modalForm.carTypes,this.carTypeOptions)
      if(this.$refs.modalForm.carTypes.length>1)
      {
        this.$refs.modalForm.carTypes.shift()
      }else {
        this.$message.error("请先导入车辆信息")
      }
    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
      this.$refs.modalForm.payAlias = '支付费用(元)'
      this.$refs.modalForm.readOnly=false;
      this.$refs.modalForm.disableBalance = false
      Object.assign(this.$refs.modalForm.carTypes,this.carTypeOptions)
      if(this.$refs.modalForm.carTypes.length>1)
      {
        this.$refs.modalForm.carTypes.shift()
        this.$refs.modalForm.defaultCarTypeId=this.$refs.modalForm.carTypes[0].value
      }else {
        this.$message.error("请先导入车辆信息")
      }
    },

    handleRecharge(record){
      this.$refs.rechargeModal.edit(record);
      this.$refs.rechargeModal.title = "充值";
      this.$refs.rechargeModal.disableSubmit = false;
    },
    handleExportXls(fileName) {

      let startTime = this.queryParam.createTime_begin;
      let endTime = this.queryParam.createTime_end;
      let dayTime = startTime;

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }

      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {...this.queryParam};
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.createTime_begin = this.queryParam.createTime_begin + " 00:00:00";
        param.createTime_end = this.queryParam.createTime_end + " 23:59:59";
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },


    onChangeStartTime(date, dateString) {
      this.queryParam.createTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.createTime_end = dateString;
    },

    searchQuery() {
      let startTime = this.queryParam.createTime_begin;
      let endTime = this.queryParam.createTime_end;

      if (startTime != "" && endTime != "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }

      this.loadData(1);
    },

    getQueryParams() {

      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.createTime_begin != "" && this.queryParam.createTime_end != "") {
        param.createTime_begin = this.queryParam.createTime_begin + " 00:00:00";
        param.createTime_end = this.queryParam.createTime_end + " 23:59:59";
      }

      // delete param.createTimeRange; // 时间参数不传递后台
      return filterObj(param);
    },
    loadCarTypeData() {
      getAction(this.url.carTypeLoad).then(res=>{
        if(res.result)
        {
           this.carTypeOptions = [{value:'',label:'请选择储值车类型'}]
           res.result.forEach(carType=>{
             this.carTypeOptions.push({
               key:carType.id,
               label:carType.carTypeName,
               value:carType.id
             })
           })
        }else {
          this.$message.error(res.message)
        }
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    keyupEnter() {
      document.onkeydown = e => {
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },
    Refresh(){
      this.loadData();
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
